<template>
  <div class="charts-page">
    <NavBar title="图表展示" :show-home-button="true">
      <template #right>
        <van-icon name="plus" size="20" @click="showAddChart = true" />
      </template>
    </NavBar>
    
    <div class="page-container">
      <!-- 图表类型选择 -->
      <div class="chart-types card">
        <h3 class="section-title">图表类型</h3>
        <van-tabs v-model:active="activeTab" @change="handleTabChange">
          <van-tab title="全部" />
          <van-tab title="折线图" />
          <van-tab title="柱状图" />
          <van-tab title="饼图" />
          <van-tab title="雷达图" />
        </van-tabs>
      </div>

      <!-- 图表列表 -->
      <div class="chart-list">
        <div v-if="loading" class="loading-container">
          <van-loading type="spinner" size="24px">加载中...</van-loading>
        </div>
        <div v-else-if="filteredCharts.length === 0" class="empty-container">
          <van-empty description="暂无图表数据" />
        </div>
        <div v-else>
          <div
            v-for="chart in filteredCharts"
            :key="chart.id"
            class="chart-item"
            @click="viewChart(chart)"
          >
            <BaseChart
              :title="chart.title"
              :type="chart.type"
              :data="chart.data"
              :height="chartHeight"
            >
              <template #actions>
                <van-icon
                  name="edit"
                  size="16"
                  @click.stop="editChart(chart)"
                />
                <van-icon
                  name="delete-o"
                  size="16"
                  @click.stop="deleteChart(chart.id)"
                />
              </template>
            </BaseChart>
          </div>
        </div>
      </div>
    </div>

    <!-- 添加图表弹窗 -->
    <van-popup
      v-model:show="showAddChart"
      position="bottom"
      :style="{ height: '60%' }"
      round
    >
      <div class="popup-header">
        <h3>添加图表</h3>
        <van-icon name="cross" @click="showAddChart = false" />
      </div>
      <div class="popup-content">
        <van-form @submit="onSubmit">
          <van-field
            v-model="formData.title"
            name="title"
            label="图表标题"
            placeholder="请输入图表标题"
            :rules="[{ required: true, message: '请输入图表标题' }]"
          />
          <van-field name="type" label="图表类型">
            <template #input>
              <van-radio-group v-model="formData.type" direction="horizontal">
                <van-radio name="line">折线图</van-radio>
                <van-radio name="bar">柱状图</van-radio>
                <van-radio name="pie">饼图</van-radio>
                <van-radio name="radar">雷达图</van-radio>
              </van-radio-group>
            </template>
          </van-field>
          <div style="margin: 16px;">
            <van-button round block type="primary" native-type="submit">
              创建图表
            </van-button>
          </div>
        </van-form>
      </div>
    </van-popup>

    <TabBar />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { showToast, showConfirmDialog } from 'vant'
import NavBar from '@/components/NavBar.vue'
import TabBar from '@/components/TabBar.vue'
import BaseChart from '@/components/BaseChart.vue'
import { useAppStore } from '@/stores'
import { mockApi } from '@/api'
import type { ChartData } from '@/stores'

const appStore = useAppStore()

// 响应式数据
const loading = ref(false)
const activeTab = ref(0)
const showAddChart = ref(false)
const chartHeight = ref('250px')

// 表单数据
const formData = ref({
  title: '',
  type: 'line' as 'line' | 'bar' | 'pie' | 'radar'
})

// 图表类型映射
const chartTypeMap = ['', 'line', 'bar', 'pie', 'radar']

// 过滤后的图表数据
const filteredCharts = computed(() => {
  const charts = appStore.chartList
  if (activeTab.value === 0) {
    return charts
  }
  const targetType = chartTypeMap[activeTab.value]
  return charts.filter(chart => chart.type === targetType)
})

// 处理标签页切换
const handleTabChange = (index: number) => {
  activeTab.value = index
}

// 查看图表详情
const viewChart = (chart: ChartData) => {
  showToast(`查看图表: ${chart.title}`)
  // 这里可以跳转到图表详情页面
}

// 编辑图表
const editChart = (chart: ChartData) => {
  showToast(`编辑图表: ${chart.title}`)
  // 这里可以打开编辑弹窗
}

// 删除图表
const deleteChart = async (id: string) => {
  try {
    await showConfirmDialog({
      title: '确认删除',
      message: '确定要删除这个图表吗？',
    })
    
    appStore.removeChart(id)
    showToast('删除成功')
  } catch (error) {
    // 用户取消删除
  }
}

// 提交表单
const onSubmit = () => {
  if (!formData.value.title.trim()) {
    showToast('请输入图表标题')
    return
  }

  // 生成模拟数据
  const mockData = generateMockData(formData.value.type)
  
  const newChart: ChartData = {
    id: Date.now().toString(),
    title: formData.value.title,
    type: formData.value.type,
    data: mockData
  }

  appStore.addChart(newChart)
  showToast('创建成功')
  
  // 重置表单
  formData.value = {
    title: '',
    type: 'line'
  }
  showAddChart.value = false
}

// 生成模拟数据
const generateMockData = (type: string) => {
  switch (type) {
    case 'line':
    case 'bar':
      return [
        { name: '1月', value: Math.floor(Math.random() * 200) + 50 },
        { name: '2月', value: Math.floor(Math.random() * 200) + 50 },
        { name: '3月', value: Math.floor(Math.random() * 200) + 50 },
        { name: '4月', value: Math.floor(Math.random() * 200) + 50 },
        { name: '5月', value: Math.floor(Math.random() * 200) + 50 },
        { name: '6月', value: Math.floor(Math.random() * 200) + 50 }
      ]
    case 'pie':
      return [
        { name: '类型A', value: Math.floor(Math.random() * 300) + 100 },
        { name: '类型B', value: Math.floor(Math.random() * 300) + 100 },
        { name: '类型C', value: Math.floor(Math.random() * 300) + 100 },
        { name: '类型D', value: Math.floor(Math.random() * 300) + 100 }
      ]
    case 'radar':
      return [
        { name: '指标1', value: Math.floor(Math.random() * 100) + 50 },
        { name: '指标2', value: Math.floor(Math.random() * 100) + 50 },
        { name: '指标3', value: Math.floor(Math.random() * 100) + 50 },
        { name: '指标4', value: Math.floor(Math.random() * 100) + 50 },
        { name: '指标5', value: Math.floor(Math.random() * 100) + 50 }
      ]
    default:
      return []
  }
}

// 加载图表数据
const loadCharts = async () => {
  try {
    loading.value = true
    const charts = await mockApi.getChartList()
    
    // 清空现有图表并添加新的
    appStore.chartList.length = 0
    charts.forEach(chart => appStore.addChart(chart))
  } catch (error) {
    console.error('加载图表数据失败:', error)
    showToast('加载数据失败')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  loadCharts()
})
</script>

<style scoped>
.charts-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 80px;
}

.chart-types {
  margin-bottom: 16px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 16px;
}

.chart-list {
  min-height: 300px;
}

.chart-item {
  margin-bottom: 16px;
  cursor: pointer;
}

.loading-container,
.empty-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #ebedf0;
}

.popup-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
}

.popup-content {
  padding: 20px;
}

:deep(.van-tabs__nav) {
  background: transparent;
}

:deep(.van-tab) {
  font-size: 14px;
}

:deep(.van-radio-group--horizontal .van-radio) {
  margin-right: 16px;
}

:deep(.van-field__label) {
  font-weight: 500;
}
</style>